﻿using System.Collections;
using System.Linq;
using UnityEngine;

public class WeaponBase : MonoBehaviour
{
    protected Weapon weapon;
    private GameObject targetEnemy;
    [Header("瞄准速度")] [SerializeField] private float smoothSpeed = 5;
    [Header("移动速度")] [SerializeField] private float moveSpeed = 8;
    protected CircleCollider2D circleCollider2D;
    private GameObject parent;

    private bool canAttack = true;

    private bool initialized;

    // 瞄准
    private float rotationZOffset;
    private bool isStopRotation;

    private void Awake()
    {
        circleCollider2D = GetComponent<CircleCollider2D>();
    }

    public void Init(Weapon weapon)
    {
        this.weapon = weapon;
        initialized = true;
        rotationZOffset = transform.eulerAngles.z;
        parent = transform.parent.gameObject;
    }

    private void Update()
    {
        if (!initialized)
        {
            return;
        }

        // 寻找目标
        HandleAiming();

        // 每帧判断
        if (targetEnemy == null || targetEnemy.GetComponent<EnemyBase>().isDead) return;
        // 旋转
        HandleRotation2Enemy();
        // 攻击
        HandleAttack();
    }

    private void HandleRotation2Enemy()
    {
        if (targetEnemy != null && !isStopRotation)
        {
            RotationUtility.RotationToTarget(targetEnemy.transform, transform, rotationZOffset, smoothSpeed);
        }
    }


    private void HandleAttack()
    {
        if (targetEnemy != null && canAttack)
        {
            canAttack = false;
            isStopRotation = true;
            // 冲击目标
            StartCoroutine(GoEnemyPos());
        }
    }

    private IEnumerator GoEnemyPos()
    {
        Vector3 targetPos = new Vector3(targetEnemy.transform.position.x,
            targetEnemy.transform.position.y + targetEnemy.GetComponent<SpriteRenderer>().size.y / 2,
            targetEnemy.transform.position.z);
        transform.parent = null; // 关键：断开关联
        circleCollider2D.enabled = true;
        while (true)
        {
            if (targetEnemy == null)
            {
                break;
            }

            if (Vector2.Distance(this.transform.position, targetPos) < 0.1f)
            {
                break;
            }

            transform.position = Vector2.MoveTowards(this.transform.position, targetPos, moveSpeed * Time.deltaTime);
            yield return null;
        }

        StartCoroutine(GoBack());
    }

    private IEnumerator GoBack()
    {
        circleCollider2D.enabled = false;
        isStopRotation = false;
        transform.parent = parent.transform; // 关键：断开关联
        while (Vector2.Distance(Vector2.zero, transform.localPosition) > 0.1f)
        {
            transform.localPosition =
                Vector2.MoveTowards(transform.localPosition, Vector2.zero, moveSpeed * Time.deltaTime);
            yield return null;
        }

        transform.localPosition = Vector2.zero;
        StartCoroutine(AttackCooldown());
    }

    IEnumerator AttackCooldown()
    {
        yield return new WaitForSeconds(weapon.cooling);
        canAttack = true;
    }

    private void HandleAiming()
    {
        //射线检测周边半径内敌人的列表
        Collider2D[] enemies = Physics2D.OverlapCircleAll(transform.position, weapon.range, LayerMask.GetMask("Enemy"));
        if (enemies.Length > 0)
        {
            //取距离最近的
            targetEnemy = enemies.OrderBy(enemy => Vector3.Distance(transform.position, enemy.transform.position))
                .First().gameObject;
        }
        else
        {
            targetEnemy = null;
        }
    }
}